package com.arcticcoding.util.serializer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import org.apache.commons.io.IOUtils;

import android.util.Log;

import com.arcticcoding.dto.ImageFrame;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;

public class ImageFrameSerializer extends Serializer<ImageFrame> {
	private static final String TAG = "com.arcticcoding.nxtphone.ImageFrameSerializer";
	private ByteArrayOutputStream bos;
	private GZIPOutputStream gos;
	
	public ImageFrameSerializer() {
		bos = new ByteArrayOutputStream();
		try {
			gos = new GZIPOutputStream(bos);
		} catch (IOException ex) {
			Log.e(TAG, "could not initialize gzip os", ex);
		}
	}
	
	@Override
	public void read(Kryo kryo, Input input,
			ImageFrame fram) {
		
		ImageFrame frame = new ImageFrame(new byte[]{});
		
		int len = input.readInt();
		byte[] ba = new byte[len];
		input.readBytes(ba);
	
		try {
			GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(ba));
			byte[] data = IOUtils.toByteArray(gis);
			frame.imageData = data;
		} catch (Exception ex) {
			Log.e(TAG, "could not deserialize cam frame", ex);
		}
		
//		return frame;
	}
	
	

	@Override
	public void write(Kryo kryo, Output output, ImageFrame frame) {
		try {
			gos.write(frame.imageData);
		} catch (IOException ex) {
			Log.e(TAG, "error writing cam frame", ex);
		}
		byte[] ba = bos.toByteArray();
		output.writeInt(ba.length);
		output.writeBytes(ba);
	}
	
	

}
